// NPC Class
#pragma once
#include "GameObject.h"
#include <vector>

// NPC States for State Machine
enum NPCState
{
    NPC_STATE_IDLE,        // Idle state
    NPC_STATE_PATROL,      // Patrol state
    NPC_STATE_CHASE,       // Chase player
    NPC_STATE_ATTACK,      // Attack player
    NPC_STATE_RETREAT,     // Retreat when low health
    NPC_STATE_DEAD         // Dead state
};

// Forward declaration
class NPCGroup;

class NPC : public GameObject
{
public:
    NPC();
    virtual ~NPC();

    bool Initialize(LPDIRECT3DDEVICE9 device, const D3DXVECTOR3& spawnPos);
    void Update(float deltaTime) override;
    void Render(LPDIRECT3DDEVICE9 device) override;
    void Cleanup() override;

    // State Machine
    void SetState(NPCState newState);
    NPCState GetState() const { return m_currentState; }

    // Combat
    void TakeDamage(float damage);
    bool IsDead() const { return m_health <= 0.0f; }
    float GetHealth() const { return m_health; }
    void Attack(GameObject* target);

    // AI
    void SetTarget(GameObject* target) { m_pTarget = target; }
    GameObject* GetTarget() const { return m_pTarget; }
    void SetGroup(NPCGroup* group) { m_pGroup = group; }
    NPCGroup* GetGroup() const { return m_pGroup; }

    // Movement
    void SetPatrolPoint(const D3DXVECTOR3& point) { m_patrolPoint = point; }
    D3DXVECTOR3 GetSpawnPosition() const { return m_spawnPosition; }
    void SetTerrain(class Terrain* terrain) { m_pTerrain = terrain; }
    void SetObstacles(const std::vector<GameObject*>* obstacles) { m_pObstacles = obstacles; }

    // Properties
    float GetSpeed() const { return m_speed; }
    float GetViewRange() const { return m_viewRange; }
    float GetAttackRange() const { return m_attackRange; }

private:
    void UpdateState(float deltaTime);
    void UpdateIdle(float deltaTime);
    void UpdatePatrol(float deltaTime);
    void UpdateChase(float deltaTime);
    void UpdateAttack(float deltaTime);
    void UpdateRetreat(float deltaTime);

    void MoveTowards(const D3DXVECTOR3& target, float deltaTime);
    float DistanceToTarget() const;

    // Model and rendering
    LPD3DXMESH m_pMesh;
    LPDIRECT3DTEXTURE9 m_pTexture;

    // State machine
    NPCState m_currentState;
    float m_stateTime;

    // Combat stats
    float m_health;
    float m_maxHealth;
    float m_attackDamage;
    float m_attackCooldown;
    float m_currentCooldown;

    // AI properties
    GameObject* m_pTarget;
    NPCGroup* m_pGroup;
    class Terrain* m_pTerrain;
    const std::vector<GameObject*>* m_pObstacles;
    D3DXVECTOR3 m_spawnPosition;
    D3DXVECTOR3 m_patrolPoint;

    // Movement
    float m_speed;
    float m_viewRange;
    float m_attackRange;
    float m_retreatHealthThreshold;
};
